package com.laicunba.ext.web.controller.h5.template;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.laicunba.constant.GloabConstant;
import com.laicunba.ext.service.SlaveActivityJoinService;
import com.laicunba.ext.web.controller.SuiCunBaoBaseController;
import com.laicunba.pojo.ActivityDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.pojo.vo.WeiXinVO;
import com.laicunba.service.ActivityService;
import com.laicunba.service.PicService;
import com.laicunba.service.UserService;
import com.laicunba.service.VcoinWalletService;
import com.laicunba.service.WeiXinService;
import com.laicunba.service.impl.helper.JsScriptRedisHelper;
import com.laicunba.util.DateUtil;
import com.laicunba.util.QRcodeUtil;
import com.laicunba.util.StringUtil;

/**
 * 破50亿感恩活动
 * 
 * @author lws
 *
 */
@Controller
@RequestMapping(value = "/h5/ext/template")
public class Exceed5billionActivityController extends SuiCunBaoBaseController {
	private static final Logger LOG = Logger.getLogger(Exceed5billionActivityController.class);
	
	@Autowired
	private ActivityService activityService;
	@Autowired
	private VcoinWalletService vcoinWalletService;
	@Autowired
	private SlaveActivityJoinService slaveActivityJoinService;
	@Autowired
	private WeiXinService weiXinService;
	@Autowired
	private UserService userService;
	@Autowired
	private PicService picService;
	@Value("${ftp.dir:/resource/}")
	private String ftpDir;
	
	/**
	 * 访问破50亿活动页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/exceed_5billion_activity_go_invite.htm")
	public ModelAndView exceed5billionActivityGoInvite(HttpServletRequest request) { 
		ModelAndView view = new ModelAndView("exceed_5billion_activity.vm");
		view.addObject("device", request.getParameter("device"));
		view.addObject("app_token", request.getParameter("app_token"));
		try {
			ActivityDO activity = activityService.get(ActivityDO.class, "20170905act");
			if (activity == null || activity.getBeginTime().after(new Date())){
				view.addObject("activityNoBegin", 1);
			}
			if(activity != null && activity.getEndTime().before(new Date())) {
				view.addObject("activityEnd", 1);
			}
			// 最新兑换记录
			try {
				List<Map<String, Object>> newRewardRecordList = slaveActivityJoinService.findUserRewardList("20170905act", "005", null, 10);
				for (Map<String, Object> rewardRecordMap : newRewardRecordList) {
					String userId = rewardRecordMap.get("userid")!=null ? rewardRecordMap.get("userid").toString() : "";
					UserDO userDO = userService.get(UserDO.class, userId);
					if (userDO != null) {
						rewardRecordMap.put("userMobile", userDO.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
					}
				}
				addMockData(newRewardRecordList);
				view.addObject("newRewardRecordList", newRewardRecordList);
			} catch (ParseException e) {
				LOG.error("进入破50亿感恩活动页面，获取最新兑换记录出现错误！" + e);
			}
			
			UserDO user = getCurrentUser(request);
			if(user == null) {
				return view;
			} 
			int days = DateUtil.days(activity.getBeginTime(), activity.getEndTime());
			JsScriptRedisHelper redisHelper = new JsScriptRedisHelper();
			// 获得积分
			String currentUserIsCleared = redisHelper.getAttribute("act.5billion.20170905" + user.getId() + ".clean-act20170905-vcoin");
			if (StringUtil.isEmpty(currentUserIsCleared) || !currentUserIsCleared.equals("1")) {
				long balance = vcoinWalletService.getBalance(user.getId());
				if(balance > 0) {
					vcoinWalletService.subtract(user.getId(), (int) balance, "CELEBRATE_5_BILLION_ACTIVITY_CLEAN", "破50亿活动上线前积分清零");
				}
				redisHelper.setAttribute("act.5billion.20170905" + user.getId() + ".clean-act20170905-vcoin", "1", days * 24 * 60 * 60);
			}
			view.addObject("act5billionUserVcoin", vcoinWalletService.getBalance(user.getId()));
			
			String currentOpenBoxChange = redisHelper.getAttribute("act.5billion.2017openboxchange." + user.getId());
			String currentLotteryDrawChance = redisHelper.getAttribute("act.5billion.2017lotterydrawchance." + user.getId());
			String currentLotteryDrawPacket = redisHelper.getAttribute("act.5billion.2017lotterydrawpacket." + user.getId());
			int currentUserOpenBoxChange = StringUtil.isEmpty(currentOpenBoxChange) ? 0 : Integer.parseInt(currentOpenBoxChange);
			// 活动期间注册用户赠送开启宝箱机会
			if(activity != null && activity.getBeginTime().before(user.getGmtCreate()) && activity.getEndTime().after(user.getGmtCreate())) {
				String isSendOpenBoxChange = redisHelper.getAttribute("act.5billion.2017sendopenboxchange." + user.getId());
				if (StringUtil.isEmpty(isSendOpenBoxChange) || Integer.parseInt(isSendOpenBoxChange) == 0) {
					currentUserOpenBoxChange = currentUserOpenBoxChange + 1;
					redisHelper.setAttribute("act.5billion.2017sendopenboxchange." + user.getId(), "1", days * 24 * 60 * 60);
					redisHelper.setAttribute("act.5billion.2017openboxchange." + user.getId(), String.valueOf(currentUserOpenBoxChange), days * 24 * 60 * 60);
				}
			}
			
			view.addObject("currentOpenBoxChange", currentUserOpenBoxChange);
			view.addObject("currentLotteryDrawChance", StringUtil.isEmpty(currentLotteryDrawChance) ? 0: currentLotteryDrawChance);
			view.addObject("currentLotteryDrawPacket", StringUtil.isEmpty(currentLotteryDrawPacket) ? 0: currentLotteryDrawPacket);
			
			String uri = request.getRequestURI();
			uri = uri.substring(request.getContextPath().length());
			String link = GloabConstant.WEB_PATH + uri;
			if(StringUtil.isNotEmpty(request.getQueryString())) {
				link += "?" + request.getQueryString();
			}
			if (StringUtil.isEmpty(user.getInviteCode())) {
				// 生成邀请码
				user.setInviteCode(getRandomString());
			}
			if (StringUtil.isEmpty(user.getInviteQrCode()) && StringUtil.isNotEmpty(user.getInviteCode())) {
				File qrcodeDir = new File(GloabConstant.PIC_ROOT + "/invite/");
				if (!qrcodeDir.exists()) {
					qrcodeDir.mkdirs();
				}
				File qrCodeFile = new File(qrcodeDir, user.getId() + ".png");
				try {
					QRcodeUtil.make(GloabConstant.WEB_PATH + "/h5/regist_new.jsp?invite_code=" + user.getInviteCode()
							+"&mobile="+user.getMobile().toString().substring(0,3)+"****"+user.getMobile().toString().substring(7), qrCodeFile, 300, 300);
					user.setInviteQrCode("invite/" + user.getId() + ".png");
					picService.upload2Ftp(new FileInputStream(qrCodeFile), ftpDir+"invite/" + user.getId() + ".png");
					userService.updateSkipCheckOwner(user);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			WeiXinVO weiXinVO = new WeiXinVO();
			weiXinVO.setLink(link);
			LOG.info(String.format("【破50亿感恩活动上线】url=[%s]", "u." + weiXinVO.getLink()));
			weiXinVO = weiXinService.getWeiXinVO(weiXinVO);
			LOG.info(String.format("【破50亿感恩活动上线】url=[%s]", "u." + weiXinVO.getLink()));
			view.addObject("weiXinVO", weiXinVO);
			view.addObject("inviteCode", user.getInviteCode());
			
			// 我的奖品
			try {
				view.addObject("firstLabelRewardList", slaveActivityJoinService.findUserRewardList("20170905act", "004", user.getId(), null));
			} catch (ParseException e) {
				LOG.error("进入破50亿感恩活动页面，查询我的奖品出现错误！" + e);
			}
			// 兑换记录
			try {
				view.addObject("secondLabelRewardList", slaveActivityJoinService.findUserRewardList("20170905act", "005", user.getId(), null));
			} catch (ParseException e) {
				LOG.error("进入破50亿感恩活动页面，查询兑换记录出现错误！" + e);
			}
		} catch (Exception e) {
			LOG.error("进入破50亿感恩活动页面，出现错误！" + e);
		}
		
		return view;
	}
	
	// 做假兑换记录
	private void addMockData(List<Map<String, Object>> newRewardRecordList) {
		if (newRewardRecordList != null && newRewardRecordList.size() > 10) {
			return;
		}
		List<Map<String, Object>> mockRecordList = new ArrayList<Map<String, Object>>();
		mockRecordList.add(hashMap("158****9129", 70));
		mockRecordList.add(hashMap("159****4315", 100));
		mockRecordList.add(hashMap("189****6069", 35));
		mockRecordList.add(hashMap("152****7765", 20));
		mockRecordList.add(hashMap("186****2531", 85));
		mockRecordList.add(hashMap("152****6618", 10));
		mockRecordList.add(hashMap("151****7355", 15));
		mockRecordList.add(hashMap("185****5992", 75));
		mockRecordList.add(hashMap("159****4315", 100));
		int index = 10-newRewardRecordList.size();
		for (int i=0; i<index && i<mockRecordList.size(); i++) {
			newRewardRecordList.add(mockRecordList.get(i));
		}
	}
	private Map<String, Object> hashMap(String userMobile, int couponAmount) {
		Map<String, Object> mockRecordMap = new HashMap<String, Object>();
		mockRecordMap.put("userMobile", userMobile);
		mockRecordMap.put("couponamount", couponAmount);
		return mockRecordMap;
	}
	
	private String getRandomString() {
		String base = "0123456789";
		// 生成字符串从此序列中取
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		String inviteCode = sb.toString();
		List<UserDO> userDOList = userService.findListByInviteCode(inviteCode);
		if (userDOList != null && userDOList.size() > 0) {
			inviteCode = getRandomString();
		}
		return inviteCode;
	}
	
	/**
	 * 触发登录状态
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/exceed_5billion_activity_login_status.htm")
	public String exceed5billionActivityLoginStatus(HttpServletRequest request){
		JSONObject json = new JSONObject();
		UserDO user = getCurrentUser(request);
		if(user == null) {
			json.put("loginStatus", 0);
		} else {
			json.put("loginStatus", 1);
		}
		return json.toJSONString();
	}
	
	/**
	 * 点我抽奖
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/exceed_5billion_activity_clickme.htm")
	public String clickMeDraw(HttpServletRequest request){
		JSONObject json = new JSONObject();
		UserDO user = getCurrentUser(request);
		if (user == null) {
			json.put("status", "fail");
			json.put("msg", "未登录,请先登录!");
			return json.toJSONString();
		}
		ActivityDO activity = activityService.get(ActivityDO.class, "20170905act");
		if(activity == null || activity.getBeginTime().after(new Date()) || activity.getEndTime().before(new Date())) {
			json.put("status", "success");
			json.put("msg", "不在活动范围内");
			return json.toJSONString();
		}
		int days = DateUtil.days(activity.getBeginTime(), activity.getEndTime());
		JsScriptRedisHelper redisHelper = new JsScriptRedisHelper();
		String currentLotteryDrawChance = redisHelper.getAttribute("act.5billion.2017lotterydrawchance." + user.getId());
		if (StringUtil.isEmpty(currentLotteryDrawChance) || Integer.parseInt(currentLotteryDrawChance)==0) {
			json.put("status", "nolottery");
			json.put("msg", "您还未获得抽奖机会哦，快去邀请好友<br/>注册投资吧~");
			return json.toJSONString();
		}
		
		int drawCashAmount = (new Random().nextInt(6) + 1) * 5;
		json.put("cashAmount", drawCashAmount);
		json.put("msg", "恭喜您获得了" + drawCashAmount + "元红包额度！");
		// 获取总红包数
		String currentLotteryDrawPacket = redisHelper.getAttribute("act.5billion.2017lotterydrawpacket." + user.getId());
		int currentLotteryDrawPacketNums = 0;
		if (StringUtil.isNotEmpty(currentLotteryDrawPacket)) {
			currentLotteryDrawPacketNums = Integer.parseInt(currentLotteryDrawPacket);
		}
		String totalLotterPacket = String.valueOf(currentLotteryDrawPacketNums + drawCashAmount);
		String lotteryDrawChance = String.valueOf(Integer.parseInt(currentLotteryDrawChance) - 1);
		redisHelper.setAttribute("act.5billion.2017lotterydrawpacket." + user.getId(), totalLotterPacket, days * 24 * 60 * 60);
		redisHelper.setAttribute("act.5billion.2017lotterydrawchance." + user.getId(), lotteryDrawChance, days * 24 * 60 * 60);
		json.put("totalLotterPacket", totalLotterPacket);
		json.put("lotteryDrawChance", lotteryDrawChance);
		json.put("status", "success");
		return json.toJSONString();
	}
	
}
